/*
 * clock.cpp
 *
 *  Created on: Sep 26, 2013
 *      Author: killerg
 */

#include "clock.h"
#include <sys/time.h>
#include <unistd.h>
#include "util.h"

double my_clock_t::get_time() {
    timeval tv_now;
    gettimeofday(&tv_now, NULL);

    return double(tv_now.tv_usec) / 1000000.0f + double(tv_now.tv_sec);
}

int my_clock_t::get_time_ms() {
    timeval tv_now;
    gettimeofday(&tv_now, NULL);

    return tv_now.tv_sec * 1000 + tv_now.tv_usec / 1000;
}

void my_clock_t::wait_frame() {
    tm old = tm_now;
    tt_now = std::time(NULL);
    tm_now = *std::localtime(&tt_now);

    #define UPDATE_FIELD(name)    name##_jump = (old.tm_##name != tm_now.tm_##name)
    UPDATE_FIELD(yday);
    UPDATE_FIELD(mday);
    UPDATE_FIELD(wday);
    UPDATE_FIELD(year);
    UPDATE_FIELD(mon);
    UPDATE_FIELD(hour);
    UPDATE_FIELD(min);
    UPDATE_FIELD(sec);
    #undef UPDATE_FIELD

    week_jump = (wday_jump && tm_now.tm_wday == 0);

    frame_busy = frame_end - frame_start;
    frame_sleep = tick_len - frame_busy;

    if (frame_sleep > 0) {
        usleep(frame_sleep * 1000000);
        delta = tick_len;
    } else {
        delta = frame_busy;
        frame_sleep = 0.0f;
    }

    eclipse += delta;
}

bool my_clock_t::init(int fps) {
    tick_len = 1.0/fps;

    tt_now = std::time(NULL);
    tm_now = *std::localtime(&tt_now);

    return true;
}

void my_clock_t::destroy() {
    UTIL_LOG(I, "clock total last %f sec", eclipse);
}
